<?php
// Copyright 2008 Datapolis Solutions OY
// 
// This file is part of a program, that is distributed
// under the terms of the GNU General Public License,
// see license.txt for details.


require_once('dpdatabase.class.php');
require_once('IDPFormBlock.php');

abstract class DPFormBlock implements IDPFormBlock {
	
	const MAP_GOOGLE             = 'google';
	const MAP_HEL                = 'hel';
	const STATUS_USER            = 0;
	const STATUS_PREDEFINED      = 1;
	
	/** @var object Database object. */
	protected $db;
	/** @var array Miscellaneous options and parameters, see constructor and loadParams(). */
	protected $options;
	/** @var boolean True if loadParams() is successfully called. */
	protected $paramsLoaded;
	/** @var array  Error messages. */
	protected $errorMsgs;
	
	/**
	* $opts is an array and it includes a number of options:
	* array(
	*   'absolute_path' => Joomla's absolute path.
	*   'live_site'     => Joomla's url.
	* )
	* 
	* @param  array  $opts  Options.
	* @return void
	*/
	public function __construct ( $opts )
	{
		$this->db        = null;
		$this->options   = array(
			'absolute_path' => '',
			'live_site'     => '',
			'icon'          => '',
			'iconUrl'       => '',
			'iconWidth'     => '',
			'iconHeight'    => '',
		);
		$this->paramsLoaded = false;
		$this->errorMsgs    = array();
		
		// check options
		$this->options['absolute_path'] = $opts['absolute_path'];
		$this->options['live_site']     = $opts['live_site'];
		$this->options['icon']          = 'components/com_dpposition/images/needle.png';
		$this->options['iconUrl']       = $this->options['live_site'].'/'.$this->options['icon'];
		$this->options['iconWidth']     = 12;
		$this->options['iconHeight']    = 12;
		
		// icon
		$iconSize = getimagesize($this->options['absolute_path'].'/'.$this->options['icon']);
		if( is_array($iconSize) ){
			$this->options['iconWidth']  = $iconSize[0];
			$this->options['iconHeight'] = $iconSize[1];
		}
		
		// load component's parameters
		$this->loadParams();
	}
	
	/**
	* Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
	* If one does exist, then the existing instance is returned.
	*/
	abstract public static function getInstance ( $opts );
	
	/**
	* Quote text for JavaScript.
	*/
	protected function jsQuote ( $str )
	{
		return "'".str_replace("'", "\\'", $str)."'";
	}
	
	protected function getJSFileUrl ( $name )
	{
		$name = substr($name, 0, strrpos($name, '.'));
		if( $this->options['useminified'] === 1 
			&& is_file($this->options['absolute_path'].'/components/com_dpposition/js/'.$name.'.min.js') ){
			return $this->options['live_site'].'/components/com_dpposition/js/'.$name.'.min.js';
		}
		return $this->options['live_site'].'/components/com_dpposition/js/'.$name.'.js';
	}
	
	protected function getCSSFileUrl ( $name )
	{
		$name = substr($name, 0, strrpos($name, '.'));
		if( $this->options['useminified'] === 1 
			&& is_file($this->options['absolute_path'].'/components/com_dpposition/css/'.$name.'.min.css') ){
			return $this->options['live_site'].'/components/com_dpposition/css/'.$name.'.min.css';
		}
		return $this->options['live_site'].'/components/com_dpposition/css/'.$name.'.css';
	}
	
	/**
	* Check class variables.
	* 
	* return boolean
	*/
	protected function selfCheck (  )
	{
		if( $this->paramsLoaded === false ){
			$this->addError(__FILE__, __LINE__, "Parameters are not loaded");
			return false;
		}
		if( strlen($this->options['database']) < 1 ){
			$this->addError(__FILE__, __LINE__, "Empty database parameter");
			return false;
		}
		if( strlen($this->options['google_map_key']) < 1 ){
			$this->addError(__FILE__, __LINE__, "Empty Google Map API Key");
			return false;
		}
		return true;
	}
	
	/**
	* Load dpposition component's parameters and Google Map API Key from #__dpjoomla table.
	* 
	* return boolean
	*/
	protected function loadParams (  )
	{
		global $database;
		
		if( $this->paramsLoaded === false ){
			$sql = "SELECT `params` 
				FROM #__components 
				WHERE
					`option`=".$database->Quote('com_dpposition')
					." AND `parent`=0"
					." LIMIT 1";
			$database->setQuery( $sql );
			$params = $database->loadResult();
			if( empty($params) === false ){
				$this->paramsLoaded = true;
				
				// create parameters object
				$p =& new mosParameters($params, $this->options['absolute_path'].'/administrator/components/com_dpposition/dpposition.xml', 'component');
				
				// get parameter values
				$this->options['database']         = $p->get('database', '');
				$this->options['map']              = $p->get('map', 'google');
				$this->options['useminified']      = intval($p->get('useminified', '0'));
				$this->options['default_status']   = intval($p->get('default_status', DPFormBlock::STATUS_USER));
				$this->options['default_list_id']  = intval($p->get('default_list_id', '1'));
				$this->options['default_map_lat']  = floatval($p->get('default_map_lat', '60.170698842241144'));
				$this->options['default_map_lon']  = floatval($p->get('default_map_lon', '24.941368103027344'));
				$this->options['default_map_zoom'] = intval($p->get('default_map_zoom', '1'));
				$this->options['max_len_name']     = intval($p->get('max_len_name', '255'));
				$this->options['max_len_street']   = intval($p->get('max_len_street', '255'));
				$this->options['max_len_details']  = intval($p->get('max_len_details', '255'));
				$this->options['dpjoomla_id']      = '';
				$this->options['google_map_key']   = '';
				//$this->options['']                 = $p->get('', '');
				
				// check database name
				if( strlen($this->options['database']) < 1 ){
					$this->addError(__FILE__, __LINE__, "Empty database parameter");
				}else{
					// create database connection
					$this->db =& DPDatabase::getInstance($this->options['database']);
					
					// get Google Map Key
					$sql = "SELECT `dpjoomla_id`, `dpjoomla_google_map_key` 
						FROM #__dpjoomla 
						WHERE
							`dpjoomla_url`=".$this->db->Quote($this->options['live_site'])
							." LIMIT 1";
					$this->db->setQuery( $sql );
					$k = $this->db->loadRow();
					if( is_array($k) === true ){
						$this->options['dpjoomla_id']    = intval($k[0]);
						$this->options['google_map_key'] = $k[1];
					}else{
						$this->addError(__FILE__, __LINE__, "Empty Google Map API Key");
					}
				}
				
				// parameters loaded
				if( $this->hasError() ){
					return false;
				}
				return true;
			}else{
				$this->addError(__FILE__, __LINE__, "Couldn't load parameters");
				return false;
			}
		}
		return true;
	}
	
	/**
	* Add error message.
	* 
	* @return void
	*/
	protected function addError ( $file, $line, $msg )
	{
		$this->errorMsgs[] = array(basename($file), $line, $msg);
	}
	
	/**
	* Add error messages.
	* 
	* @return void
	*/
	protected function appendErrors ( $errors )
	{
		$this->errorMsgs = array_merge($this->errorMsgs, $errors);
	}
	
	/**
	* True if object has an error message.
	* 
	* @return boolean
	*/
	public function hasError (  )
	{
		if( count($this->errorMsgs) > 0 ){
			return true;
		}
		return false;
	}
	
	/**
	* Get error string.
	* 
	* @return string
	*/
	public function getError (  )
	{
		$m = "";
		foreach( $this->errorMsgs as $e ){
			$m .= "{$e[0]}:{$e[1]} {$e[2]}<br />\n";
		}
		return $m;
	}
}

?>